/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.messaging;

import entity.MessageEntity;
import entity.StakeholderEntity;
import entity.OwnerEntity;
import entity.InboxEntity;
import exception.ExistException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.model.MenuModel;
import session.stateless.MessageSessionBean;
import session.stateless.StaffAccountSessionBean;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StaffAccountState;
import util.entityhelper.StakeholderAccountState;
import util.generator.StaffMenuGenerator;
import util.localization.WebLocalization;

/**
 *
 * @author KohLi
 */
@ManagedBean
@ViewScoped
public class ComposeMessageManagedBean {

    @EJB
    private MessageSessionBean messageSessionbean;
    @EJB
    private StakeholderSessionBeanStateless stakeholderSessionBean;
    @EJB
    private StaffAccountSessionBean staffSessionBean;
    @EJB
    private SystemMessagesBean systemMessages;
    private Long stakeholderId;
    private Long staffAccountId;
    private String nextPage;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private String preferredLocale;
    private WebLocalization localization;
    private MessageEntity message;
    private List<OwnerEntity> receivers;
    private List<StakeholderEntity> stakeholderList;
    private InboxEntity userMessage;
    private StakeholderAccountState stakeholder;
    private OwnerEntity toWho;
    private OwnerEntity fromWho;
    private List<StaffAccountState> staffList;
    private StaffAccountState staff;
    private String statusMessage;
    private MenuModel staffMenuModel;
    private MessageEntity replyMessage;
    private boolean aReply;

    /** Creates a new instance of ComposeMessageManagedBean */
    public ComposeMessageManagedBean() {

        // get account ID values from session
        if (ctx.getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            stakeholderId = (Long) ctx.getExternalContext().getSessionMap().get("stakeholderId");
            // put back the session IDs taken
            ctx.getExternalContext().getSessionMap().put("stakeholderId", stakeholderId);
        } else if (ctx.getExternalContext().getSessionMap().containsKey("staffAccountId")) {
            // get session values
            staffAccountId = (Long) ctx.getExternalContext().getSessionMap().get("staffAccountId");
            // put back session values
            ctx.getExternalContext().getSessionMap().put("staffAccountId", staffAccountId);
        } else {
            // redirect back to login
        }
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        userMessage = new InboxEntity();
        toWho = new OwnerEntity();
        fromWho = new OwnerEntity();
        message = new MessageEntity();
        replyMessage = new MessageEntity();
        if (ctx.getExternalContext().getSessionMap().containsKey("message")) {
            message = (MessageEntity) ctx.getExternalContext().getSessionMap().get("message");
            setaReply(true);
        } else {
            setaReply(false);
        }
    }

    public void initView(PhaseEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException {
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        if (getStakeholderId() == null && getStaffAccountId() == null) {

            setNextPage(FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml")));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(getNextPage());
            } catch (IOException ex) {
                Logger.getLogger(ComposeMessageManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            if (!ctx.getExternalContext().getSessionMap().containsKey("message")) {
                // is the stakeholder who composing the message
                if (getStaffAccountId() != null & staff == null) {
                    System.out.println("staff new composing message " + getStaffAccountId());
                    try {
                        staff = staffSessionBean.getStaffAccountByID(staffAccountId);
                        /* PRE-SET MENU BASED ON ACCESS RIGHTS */
                        StaffMenuGenerator menuGenerator = new StaffMenuGenerator(staff);
                        setStaffMenuModel(menuGenerator.generateStaffMenu());
                        /* END PRE-SET MENU BASED ON ACCESS RIGHTS */
                    } catch (ExistException ex) {
                        System.out.println(ex.getMessage());
                    }

                    //stakeholderList = stakeholderSessionBean.getAllStakeholders();
                } else if (stakeholder == null && getStakeholderId() != null) {
                    setMessageDetail();
                }
            }
            if (ctx.getExternalContext().getSessionMap().containsKey("message")) {
                System.out.println("Reply Message: composing");
                if (staff == null && staffAccountId!=null) {
                    try {
                        staff = staffSessionBean.getStaffAccountByID(staffAccountId);
                    } catch (ExistException ex) {
                        System.out.println("ex" + ex.getMessage());
                    }
                    /* PRE-SET MENU BASED ON ACCESS RIGHTS */
                    StaffMenuGenerator menuGenerator = new StaffMenuGenerator(staff);
                    setStaffMenuModel(menuGenerator.generateStaffMenu());
                    /* END PRE-SET MENU BASED ON ACCESS RIGHTS */
                }
                    
                System.out.println("msg sender +\t" + message.getSender() + "\t" + message.getReceiver());
                replyMessage.setReceiver(message.getSender());
                replyMessage.setSender(message.getReceiver());

                message.setReceiver(message.getSender());
                message.setSubject("RE: " + message.getSubject());
                message.setMessage("" + message.getMessage());
                replyMessage.setSubject(message.getSubject());
                //toWho.setName(msg.getSender());
                //fromWho.setName(msg.getReceiver());
            }
        }
    }

    private void setMessageDetail() {
        try {
            setStakeholder(stakeholderSessionBean.getStakeholderPortalInfoById(stakeholderId));
            System.out.println("who is the sender" + getStakeholder().getUsername());
            //userMessage.setSender(getStakeholder().getUsername());
            staffList = staffSessionBean.getStaffAccounts();
            System.out.println("size of staff account " + getStaffList().size());

            message.setReceiver(staffList.get(0).getUsername());
            System.out.println("staffUserName: " + staffList.get(0).getUsername());
            message.setSender(stakeholder.getUsername());
            System.out.println("stakeholder: " + stakeholder.getUsername());
            //check later who is inside.
            toWho.setName(staffList.get(0).getUsername());
            toWho.setStaff(true);
            fromWho.setName(stakeholder.getUsername());
            fromWho.setStakeholder(true);
            //System.out.println(""+getStaffList().get(0).getStaff().getEmail());
        } catch (ExistException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void replyMessage(ActionEvent event) {

        try {
            messageSessionbean.replyMessage(replyMessage);
        } catch (ExistException ex) {
            System.out.println("ex message" + ex.getMessage());
        }

    }

    public void saveMessage(ActionEvent event) {

        //System.out.println("event ticket pricing: " +eventActivity.getTicket().getPrice());
        System.out.println("The message" + message.getMessage());
        try {
            messageSessionbean.saveMessage(toWho, fromWho, message, userMessage);

            setStatusMessage(getSystemMessages().getSystemMessage("EVENT_EDIT", preferredLocale));

            //ctx.getExternalContext().getSessionMap().put("eventId", eventId);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("successmsg", getStatusMessage());
            //System.out.println("eventId" +eventId);
            redirectPage();
        } catch (ExistException ex) {
            setStatusMessage(getSystemMessages().getSystemMessage(ex.getMessage(), preferredLocale));
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, getStatusMessage(), ""));
            System.out.println("" + ex.getMessage());
        }

    }

    public void redirectPage() {
        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            FacesContext ctx = FacesContext.getCurrentInstance();
            String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().
                    getActionURL(ctx, "/messaging/Myinbox.xhtml"));
            try {
                ctx.getExternalContext().redirect(nextPage);
            } catch (IOException ex) {
            }
        } else {
            FacesContext ctx = FacesContext.getCurrentInstance();
            String nextPage = ctx.getExternalContext().encodeActionURL(ctx.getApplication().getViewHandler().
                    getActionURL(ctx, "/staff/StaffComposeMessage.xhtml"));
            try {
                ctx.getExternalContext().redirect(nextPage);
            } catch (IOException ex) {
            }
        }
    }

    public List<StaffAccountState> complete(String query) {
        List<StaffAccountState> results = new ArrayList<StaffAccountState>();
        for (int i = 0; i < getStaffList().size(); i++) {
            StaffAccountState staff = getStaffList().get(i);
            if (staff.getUsername().contains(query)) {
                results.add(staff);
            }
        }
        return results;
    }

    /**
     * @return the messageSessionbean
     */
    public MessageSessionBean getMessageSessionbean() {
        return messageSessionbean;
    }

    /**
     * @param messageSessionbean the messageSessionbean to set
     */
    public void setMessageSessionbean(MessageSessionBean messageSessionbean) {
        this.messageSessionbean = messageSessionbean;
    }

    /**
     * @return the stakeholderSessionBean
     */
    public StakeholderSessionBeanStateless getStakeholderSessionBean() {
        return stakeholderSessionBean;
    }

    /**
     * @param stakeholderSessionBean the stakeholderSessionBean to set
     */
    public void setStakeholderSessionBean(StakeholderSessionBeanStateless stakeholderSessionBean) {
        this.stakeholderSessionBean = stakeholderSessionBean;
    }

    /**
     * @return the stakeholderId
     */
    public Long getStakeholderId() {
        return stakeholderId;
    }

    /**
     * @param stakeholderId the stakeholderId to set
     */
    public void setStakeholderId(Long stakeholderId) {
        this.stakeholderId = stakeholderId;
    }

    /**
     * @return the staffAccountId
     */
    public Long getStaffAccountId() {
        return staffAccountId;
    }

    /**
     * @param staffAccountId the staffAccountId to set
     */
    public void setStaffAccountId(Long staffAccountId) {
        this.staffAccountId = staffAccountId;
    }

    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }

    /**
     * @return the ctx
     */
    public FacesContext getCtx() {
        return ctx;
    }

    /**
     * @param ctx the ctx to set
     */
    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }

    /**
     * @return the preferredLocale
     */
    public String getPreferredLocale() {
        return preferredLocale;
    }

    /**
     * @param preferredLocale the preferredLocale to set
     */
    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    /**
     * @return the localization
     */
    public WebLocalization getLocalization() {
        return localization;
    }

    /**
     * @param localization the localization to set
     */
    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    /**
     * @return the message
     */
    public MessageEntity getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(MessageEntity message) {
        this.message = message;
    }

    /**
     * @return the stakeholderList
     */
    public List<StakeholderEntity> getStakeholderList() {
        return stakeholderList;
    }

    /**
     * @param stakeholderList the stakeholderList to set
     */
    public void setStakeholderList(List<StakeholderEntity> stakeholderList) {
        this.stakeholderList = stakeholderList;
    }

    /**
     * @return the userMessage
     */
    public InboxEntity getUserMessage() {
        return userMessage;
    }

    /**
     * @param userMessage the userMessage to set
     */
    public void setUserMessage(InboxEntity userMessage) {
        this.userMessage = userMessage;
    }

    /**
     * @return the receivers
     */
    public List<OwnerEntity> getReceivers() {
        return receivers;
    }

    /**
     * @param receivers the receivers to set
     */
    public void setReceivers(List<OwnerEntity> receivers) {
        this.receivers = receivers;
    }

    /**
     * @return the stakeholder
     */
    public StakeholderAccountState getStakeholder() {
        return stakeholder;
    }

    /**
     * @param stakeholder the stakeholder to set
     */
    public void setStakeholder(StakeholderAccountState stakeholder) {
        this.stakeholder = stakeholder;
    }

    /**
     * @return the staffList
     */
    public List<StaffAccountState> getStaffList() {
        return staffList;
    }

    /**
     * @return the staff
     */
    public StaffAccountState getStaff() {
        return staff;
    }

    /**
     * @param staff the staff to set
     */
    public void setStaff(StaffAccountState staff) {
        this.staff = staff;
    }

    /**
     * @return the toWho
     */
    public OwnerEntity getToWho() {
        return toWho;
    }

    /**
     * @param toWho the toWho to set
     */
    public void setToWho(OwnerEntity toWho) {
        this.toWho = toWho;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @param systemMessages the systemMessages to set
     */
    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    /**
     * @return the statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * @param statusMessage the statusMessage to set
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     * @return the fromWho
     */
    public OwnerEntity getFromWho() {
        return fromWho;
    }

    /**
     * @param fromWho the fromWho to set
     */
    public void setFromWho(OwnerEntity fromWho) {
        this.fromWho = fromWho;
    }

    public MenuModel getStaffMenuModel() {
        return staffMenuModel;
    }

    public void setStaffMenuModel(MenuModel staffMenuModel) {
        this.staffMenuModel = staffMenuModel;
    }

    /**
     * @return the aReply
     */
    public boolean isaReply() {
        return aReply;
    }

    /**
     * @param aReply the aReply to set
     */
    public void setaReply(boolean aReply) {
        this.aReply = aReply;
    }

    /**
     * @return the replyMessage
     */
    public MessageEntity getReplyMessage() {
        return replyMessage;
    }

    /**
     * @param replyMessage the replyMessage to set
     */
    public void setReplyMessage(MessageEntity replyMessage) {
        this.replyMessage = replyMessage;
    }
}
